import random
import time
import pytest  # 引入 pytest


# 归并排序
def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        left_half = arr[:mid]
        right_half = arr[mid:]

        merge_sort(left_half)
        merge_sort(right_half)

        i = j = k = 0
        while i < len(left_half) and j < len(right_half):
            if left_half[i] < right_half[j]:
                arr[k] = left_half[i]
                i += 1
            else:
                arr[k] = right_half[j]
                j += 1
            k += 1

        while i < len(left_half):
            arr[k] = left_half[i]
            i += 1
            k += 1
        while j < len(right_half):
            arr[k] = right_half[j]
            j += 1
            k += 1

    return arr


def shell_sort(arr):
    n = len(arr)
    gap = n // 2
    while gap > 0:
        for i in range(gap, n):
            temp = arr[i]
            j = i
            while j >= gap and arr[j - gap] > temp:
                arr[j] = arr[j - gap]
                j -= gap
            arr[j] = temp
        gap //= 2


def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)


def generate_random_array(size):
    return random.sample(range(1, 500001), size)


# 在pytest中测试排序算法
@pytest.mark.parametrize("size", [1000, 10000, 100000])  # 参数化测试
def test_sorting_algorithms(size):
    print(f"\nTesting with array size: {size}")

    arr = generate_random_array(size)

    # 归并排序
    arr_copy = arr.copy()
    start_time = time.time()
    merge_sort(arr_copy)
    merge_time = time.time() - start_time
    print(f"Merge Sort Time: {merge_time:.6f} seconds")

    # 希尔排序
    arr_copy = arr.copy()
    start_time = time.time()
    shell_sort(arr_copy)
    shell_time = time.time() - start_time
    print(f"Shell Sort Time: {shell_time:.6f} seconds")

    # 快速排序
    arr_copy = arr.copy()
    start_time = time.time()
    arr_sorted = quick_sort(arr_copy)
    quick_time = time.time() - start_time
    print(f"Quick Sort Time: {quick_time:.6f} seconds")